package com.example.service;

import ch.qos.logback.classic.Logger;
import com.example.data.entity.QuestionInfo;
import com.example.data.entity.kg.KgEntity;
import com.example.data.mapper.KgEntityMapper;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * 问题分析器，用于理解问题意图和提取关键信息
 */
@Component
public class QuestionAnalyzer {

    // 新增日志对象
    private static final Logger log = (Logger) LoggerFactory.getLogger(QuestionAnalyzer.class);

    @Resource
    private NlpService nlpService;

    @Resource
    private KgEntityMapper kgEntityMapper;

    /**
     * 分析问题，提取关键信息
     */
    public QuestionInfo analyze(String question) {
        QuestionInfo questionInfo = new QuestionInfo();
        questionInfo.setOriginalQuestion(question);

        // 1. 日志：打印要分析的原始问题
        log.info("开始分析问题：{}", question);

        // 获取知识图谱中所有已知实体名称，用于实体识别
        List<KgEntity> allEntities = kgEntityMapper.selectAll();
        List<String> knownEntityNames = allEntities.stream()
                .map(KgEntity::getEntityName)
                .toList();

        // 日志：打印数据库中的已知实体（确认是否包含目标实体，如“巨鹿之战”）
        log.info("数据库中的已知实体列表：{}", knownEntityNames);

        // 提取实体
        List<String> entities = nlpService.extractEntities(question, knownEntityNames);
        questionInfo.setEntities(entities);

        // 日志：打印提取到的实体（核心！确认是否提取到目标实体）
        log.info("从问题[{}]中提取到的实体：{}", question, entities);

        // 提取关系
        String relation = nlpService.extractRelation(question);
        questionInfo.setRelationType(relation);

        // 新增日志：打印提取到的关系
        log.info("从问题[{}]中提取到的关系类型：{}", question, relation);

        // 判断是询问头实体还是尾实体
        boolean askingForHead = nlpService.isAskingForHeadEntity(question, entities);
        questionInfo.setAskingForHeadEntity(askingForHead);

        // 确定已知实体在三元组中的角色（头还是尾）
        if (!entities.isEmpty()) {
            if (askingForHead) {
                // 问题是问谁与该实体有某种关系，实体是尾实体
                questionInfo.setKnownTailEntity(entities.get(0));
            } else {
                // 问题是问该实体与谁有某种关系，实体是头实体
                questionInfo.setKnownHeadEntity(entities.get(0));
            }
        }

        return questionInfo;
    }
}
